/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.ytbolg.mcxa.gui;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import net.ytbolg.mcxa.gui.Lang_and_ConfigManager.LangManager;

/**
 *
 * @author Ytong
 */
public class DownloadWindow extends javax.swing.JFrame implements Runnable {

    JFrame self = null;
    boolean ifEnable = false;
    ArrayList<DownloadInfo> list = new ArrayList<>();
    boolean isForge = false;
    Thread Th = null;

    public void setThreadAfterFinishing(Thread th) {
        this.Th = th;

//    return Thread.currentThread();
    }

    public void setIsForge(boolean value) {
        isForge = value;
    }

    public void setSelf(JFrame jf) {
        self = jf;
    }

    public void setIfEnabld(boolean value) {
        ifEnable = value;
    }

    public DownloadWindow() {
        initComponents();
    }

    public DownloadWindow(Thread th) {
        initComponents();
        Th = th;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("下载资源中");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("微软雅黑", 0, 13)); // NOI18N
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton2.setFont(new java.awt.Font("微软雅黑", 0, 13)); // NOI18N
        jButton2.setText("取消下载");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 524, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(21, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(87, 87, 87)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(30, 30, 30))))
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        self.setEnabled(true);
        dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        jScrollPane1.getViewport().add(jTextArea1, null);
        jButton2.setText(LangManager.getStringByKey(jButton2.getText()));// TODO add your handling code here:
    }//GEN-LAST:event_formWindowOpened
    public void addDownload(String url, String to) {
        list.add(new DownloadInfo(url, to));
        //  General.Log(to, "DOWNLOAD_WINDOW-THREAD");
    }

    public void addDownload(String url, String to, String WhereToCopy) {
        list.add(new DownloadInfo(url, to, WhereToCopy));
        //  General.Log(to, "DOWNLOAD_WINDOW-THREAD");
    }
//public void setSelfWindow

    public class DownloadInfo {

        String url;
        String to;
        boolean ifcopy = false;
        String wheretoCopy = "";

        public DownloadInfo(String URL, String to) {
            this.url = URL;
            this.to = to;
        }

        public DownloadInfo(String URL, String to, String Copyto) {
            this.url = URL;
            this.to = to;
            this.ifcopy = true;
            this.wheretoCopy = Copyto;
        }

        public boolean ifCopy() {
            return ifcopy;
        }

        public String getURL() {
            return url;
        }

        public String getTO() {
            return to;
        }

        public String getWhereToCopy() {
            return wheretoCopy;
        }

    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton jButton1;
    public javax.swing.JButton jButton2;
    public javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel2;
    public javax.swing.JProgressBar jProgressBar1;
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void run() {
        try {
            General.Log("DownloadWindow","下载数目:"+list.size());
            setVisible(true);
            jTextArea1.setLineWrap(true);
            for (int i = 0; i < list.size(); i++) {
                DownloadInfo di = list.get(i);
                jTextArea1.setText(jTextArea1.getText() + "\n" + "(" + (i + 1) + "/" + (list.size()) + ")" + LangManager.getStringByKey("下载") + list.get(i).getURL() + LangManager.getStringByKey("到") + list.get(i).getTO());
       //         downloadFile(, null);
                //     tmp.join();

                downloadFile(di.getURL(), di.getTO());
                if (di.ifcopy) {
                    CommonTools.fileChannelCopy(new File(di.getTO()), new File(di.getWhereToCopy()));
                }
                jTextArea1.setCaretPosition(jTextArea1.getText().length());
            }
            if (Th != null) {
                Th.start();
            }
            // General.Log("尼玛啊", "Test");
            //   JOptionPane.showMessageDialog(rootPane, LangManager.getStringByKey("下载完成！！！！！！！！！！！！！！！"));
            //General.Log("尼玛啊", "Test");
            if (isForge == false) {
                if (self != null) {
                    this.self.setEnabled(true);
                }
                dispose();
            } else {
                JOptionPane.showMessageDialog(rootPane, LangManager.getStringByKey("Forge下载完成,下面将会运行Forge安装程序，请选择当前游戏目录（已复制到剪贴板）"));
                setSystemClipboard(General.GameDir);
                Runtime.getRuntime().exec("java -jar \"" + list.get(0).getTO() + "\"");
                if (self != null) {
                    this.self.setEnabled(true);
                }
//Thread.yield();
// Th.resume();
                dispose();

            }
            //      throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        } catch (IOException ex) {
            Logger.getLogger(DownloadWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setSystemClipboard(String refContent) {
//设置为static是为了直接使用，不用new一个该类的实例即可直接使用,即定义的: 类名.方法名  
        String vc = refContent.trim();
        StringSelection ss = new StringSelection(vc);

        Clipboard sysClb = null;
        sysClb = Toolkit.getDefaultToolkit().getSystemClipboard();
        sysClb.setContents(ss, null);

        //Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);  //跟上面三行代码效果相同  
    }

    public void downloadFile(String remoteFilePath, String localFilePath) {
        try {
            General.Log(remoteFilePath + " To " + localFilePath, "DownLoad-THREAD");
//      General.Log("下载" + remoteFilePath + "到" + localFilePath + "中", CommonTools.class.getSimpleName());
            URL urlfile = null;
            HttpURLConnection httpUrl = null;
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            File f = new File(localFilePath);
            //  File xxxx = new File(f.getParent());
            f.getParentFile().mkdirs();
            if (f.exists() == false) {
                f.createNewFile();
            }

//      f.mkdirs();
            try {
                urlfile = new URL(remoteFilePath);
                httpUrl = (HttpURLConnection) urlfile.openConnection();
                httpUrl.connect();
                jProgressBar1.setMaximum(httpUrl.getContentLength());
                jProgressBar1.setValue(0);
                bis = new BufferedInputStream(httpUrl.getInputStream());
                bos = new BufferedOutputStream(new FileOutputStream(f));
                int len = 2048;
                byte[] b = new byte[len];
                int i = 0;
                while ((len = bis.read(b)) != -1) {
                    i = i + len;
                    jProgressBar1.setValue(i);
                    jLabel1.setText(i / 1024 + "/" + (httpUrl.getContentLength() / 1024) + "KB");
                    bos.write(b, 0, len);
                }
                bos.flush();
                bis.close();
                httpUrl.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(DownloadWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
